import React, { useEffect, useRef, useState } from 'react';
import { ArrowLeft, Setting } from '@nutui/icons-react';
import { Success, Cross } from '@react-vant/icons';
import { Button, Cell } from 'react-vant';
import { useNavigate } from 'react-router-dom';
import { Popover, Toast } from 'antd-mobile';
import axios from 'axios';
import "../styles/Face.less"

export default function Addface() {
  const [currentImage, setCurrentImage] = useState("sxt2.png");
  const [cameraOn, setCameraOn] = useState(false);
  const videoRef = useRef(null);
  const navigate = useNavigate();
  const [flag, setFlag] = useState(false);
  const [flag1, setFlag1] = useState(false);
  const canvasRef = useRef(null);
  const [capturedImages, setCapturedImages] = useState([]);
  const [face_id, setface_id] = useState('')

  // 打开摄像头
  const startCamera = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      videoRef.current.srcObject = stream;
      setCameraOn(true);
    } catch (error) {
      console.log('访问摄像头出错：', error);
    }
  };

  // 关闭摄像头
  const closeMedia = () => {
    if (videoRef.current.srcObject) {
      const stream = videoRef.current.srcObject;
      const tracks = stream.getTracks();
      tracks.forEach(track => {
        track.stop();
      });
      videoRef.current.srcObject = null;
      setCameraOn(false);
    }
  };

  useEffect(() => {
    startCamera();
    console.log(sessionStorage.getItem('user'));

  }, []);

  // 切换摄像头状态和图片
  const toggleCameraAndImage = () => {
    if (cameraOn) {
      setCurrentImage('sxt1.png');
      closeMedia();
    } else {
      setCurrentImage('sxt2.png');
      startCamera();
    }
  };

  // 捕获图像
  const capture = () => {
    if (!canvasRef.current || !videoRef.current) return;

    const canvas = canvasRef.current;
    const context = canvas.getContext('2d');
    context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
    const imageSrc = canvas.toDataURL('image/jpeg');
    setCapturedImages([...capturedImages, imageSrc]);
    submitImages(imageSrc);
    setFlag(false);
    setFlag1(false);
  };
  const submitImages = async (img) => {
    try {
      setFlag(false);
      setFlag1(false);
      const res = await axios.post('http://127.0.0.1:3000/jxy/addface', { b64: img, _id: 1001 });
      setface_id(res.data.bbb)
      if (res.data.code === 200) {
        let _id = JSON.parse(sessionStorage.getItem('user'))._id
        axios.post(`http://127.0.0.1:3000/jxy/shiming?_id=${_id}&face_id=${res.data.bbb}`)
        setFlag(true);
        setTimeout(() => {
          setFlag(false);
          // 原本这里会进行页面导航和显示成功提示，现在注释掉了
          navigate('/login');
          Toast.show({
            icon: 'success',
            content: '注册成功',
          });
        }, 1500);
      }
      if (res.data.code === 401) {
        setFlag1(true);
        setTimeout(() => {
          setFlag1(false);
          Toast.show({
            icon: 'fail',
            content: '请重新验证',
          });
        }, 2000);
      }
    } catch (error) {
      console.log('提交图像出错', error);
      setFlag1(true);
    }
  };

  return (
    <div>
      <div className="face_header">
        <p style={{ marginTop: '0.1rem', width: '15%' }} onClick={() => navigate('/login')}>
          <ArrowLeft />
        </p>
        <p style={{ width: '70%', textAlign: 'center' }}>实名认证</p>
        <p style={{ animation: 'bounce 1s linear infinite', style: '15%' }}>
          <img src='/register.png' alt='' style={{ width: '0.63rem' }} className='bounce' />
        </p>
      </div>
      <p>
        <span style={{ fontSize: '14px', paddingLeft: '35px', color: 'red', display: flag1 ? 'block' : 'none' }}>
          请选择使用验证码或重新进行认证
        </span>
      </p>
      <div style={{ marginTop: '70px', height: 'auto', position: 'relative' }}>
        <Cell>
          <div className="jxy_face_kl">
            <video ref={videoRef} autoPlay muted></video>
            <canvas ref={canvasRef} style={{ display: 'none' }}></canvas>
          </div>
        </Cell>
        <Button onClick={capture} style={{ width: '50%', margin: '50px auto' }} color='linear-gradient(to right, rgb(78,115,223), rgb(2,167,240))' type='primary' block round>
          开始录取
        </Button>
        <div className='jxy_face_mask_err' style={{ display: flag1 ? 'block' : 'none' }}>
          <Cross className='jxy_face_icon1' style={{ color: 'white', fontSize: '60px' }} />
        </div>
        <div className='jxy_face_mask_success' style={{ display: flag ? 'block' : 'none' }}>
          <Success className='jxy_face_icon1' style={{ color: 'white', fontSize: '60px' }} />
        </div>
      </div>
      <Popover
        content={
          <>
            <img
              src={currentImage}
              style={{ width: '0.45rem', height: '0.35rem' }}
              alt=""
              onClick={toggleCameraAndImage}
            />
          </>
        }
        trigger="click"
        placement="left-end"
      >
        <div style={{
          width: '35px',
          height: '35px',
          position: 'fixed',
          bottom: '70px',
          right: '20px',
          border: '1px solid #d5d5d5',
          borderRadius: '50px',
          textAlign: "center",
          lineHeight: "42px"
        }}>
          <Setting />
        </div>
      </Popover>
    </div>
  );
}